package com.sk.weichat.ui.me;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.bean.Report;
import com.sk.weichat.bean.message.ChatMessage;
import com.sk.weichat.bean.message.NewFriendMessage;
import com.sk.weichat.bean.message.XmppMessage;
import com.sk.weichat.broadcast.CardcastUiUpdateUtil;
import com.sk.weichat.broadcast.MsgBroadcast;
import com.sk.weichat.db.InternationalizationHelper;
import com.sk.weichat.db.dao.ChatMessageDao;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.db.dao.NewFriendDao;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.helper.FriendHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.message.ChatBackgroundActivity;
import com.sk.weichat.ui.message.single.SetLabelActivity;
import com.sk.weichat.ui.message.single.SetRemarkActivity;
import com.sk.weichat.util.AsyncUtils;
import com.sk.weichat.util.ChangeBackgroundHelper;
import com.sk.weichat.util.TimeUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.view.ReportDialog;
import com.sk.weichat.view.SelectionFrame;
import com.sk.weichat.xmpp.ListenerManager;
import com.sk.weichat.xmpp.listener.ChatMessageListener;
import com.sk.weichat.xmpp.listener.NewFriendListener;
import com.suke.widget.SwitchButton;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 设置—通用
 * create by swy 2019-06-28
 */
public class SettingGeneralActivity extends BaseActivity implements  View.OnClickListener, ChangeBackgroundHelper.OnBackgroundChangeListener {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting_general);
        initActionBar();
        initView();
        //需要先注册事件
        ChangeBackgroundHelper.registOnBackgroundChangeListener(getApplicationContext(),this,ChangeBackgroundHelper.DefaultChatID);
    }

    private void initActionBar() {
        getSupportActionBar().hide();
        findViewById(R.id.mergerStatus).setBackgroundColor(ContextCompat.getColor(this,R.color.white));
        TextView tvTitle = (TextView) findViewById(R.id.tv_title_center);
        tvTitle.setText(R.string.setting_general);
        findViewById(R.id.iv_title_left).setOnClickListener(this);
        findViewById(R.id.layout_general_chat_background).setOnClickListener(this);
    }

    private void initView() {
        findViewById(R.id.layout_general_clear_history).setOnClickListener(this);
        findViewById(R.id.layout_general_chat_font).setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_title_left:
                finish();
                break;

            case R.id.layout_general_clear_history://清除所有聊天记录
                SelectionFrame selectionFrame = new SelectionFrame(this);
                selectionFrame.setSomething(null, getString(R.string.is_empty_all_chat), new SelectionFrame.OnSelectionFrameClickListener() {
                    @Override
                    public void cancelClick() {

                    }

                    @Override
                    public void confirmClick() {
                        emptyServerMessage();

                        // 清除所有聊天记录
                        delAllChatRecord();
                    }
                });
                selectionFrame.show();
                break;

            case R.id.layout_general_chat_font://设置聊天字体
                startActivity(new Intent(mContext, FontSizeActivity.class));
                break;

            case R.id.layout_general_chat_background:
                //设置全局背景图
                ChatBackgroundActivity.startChatBackgroundActivity(mContext,ChangeBackgroundHelper.DefaultChatID);
                break;
        }
    }

    /**
     * 服务器上所有的单人聊天记录也需要删除
     */
    private void emptyServerMessage() {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("type", String.valueOf(1));// 0 清空单人 1 清空所有

        HttpUtils.get().url(coreManager.getConfig().EMPTY_SERVER_MESSAGE)
                .params(params)
                .build()
                .execute(new BaseCallback<Void>(Void.class) {

                    @Override
                    public void onResponse(ObjectResult<Void> result) {

                    }

                    @Override
                    public void onError(Call call, Exception e) {

                    }
                });
    }

    /**
     * 清空所有聊天记录
     */
    private void delAllChatRecord() {
        DialogHelper.showDefaulteMessageProgressDialog(this);
        AsyncUtils.doAsync(this, settingActivityAsyncContext -> {
            // 不需要查询出所有好友，只需查询出最近聊天的好友即可
/*
            List<Friend> mAllFriend = new ArrayList<>();
            // 我的设备
            List<Friend> allDevices = FriendDao.getInstance().getDevice(mLoginUserId);
            mAllFriend.addAll(allDevices);
            // 公众号
            List<Friend> allSystems = FriendDao.getInstance().getAllSystems(mLoginUserId);
            mAllFriend.addAll(allSystems);
            // 我的好友
            List<Friend> allFriends = FriendDao.getInstance().getAllFriends(mLoginUserId);
            mAllFriend.addAll(allFriends);
            // 我的群组
            List<Friend> allRooms = FriendDao.getInstance().getAllRooms(mLoginUserId);
            mAllFriend.addAll(allRooms);
*/
            List<Friend> mNearChatFriendList = FriendDao.getInstance().getNearlyFriendMsg(coreManager.getSelf().getUserId());

            for (int i = 0; i < mNearChatFriendList.size(); i++) {
                if (!mNearChatFriendList.get(i).getUserId().equals(Friend.ID_SYSTEM_MESSAGE)){//过滤掉悦聊团队  保留悦聊团队入口
                    FriendDao.getInstance().resetFriendMessage(coreManager.getSelf().getUserId(), mNearChatFriendList.get(i).getUserId());
                    ChatMessageDao.getInstance().deleteMessageTable(coreManager.getSelf().getUserId(), mNearChatFriendList.get(i).getUserId());
                }
            }

            runOnUiThread(() -> {
                // 更新消息界面
                DialogHelper.dismissProgressDialog();
                MsgBroadcast.broadcastMsgUiUpdate(SettingGeneralActivity.this);
                MsgBroadcast.broadcastMsgNumReset(SettingGeneralActivity.this);
//                ToastUtil.showToast(SettingGeneralActivity.this, InternationalizationHelper.getString("JXAlert_DeleteOK"));
                ToastUtil.showToast(SettingGeneralActivity.this, R.string.delete_ok);
            });
        });
    }

    @Override
    protected void onDestroy() {
        ChangeBackgroundHelper.unRegistOnBackgroundChangeListener(ChangeBackgroundHelper.DefaultChatID);
        super.onDestroy();
    }

    @Override
    public void handle(boolean isReset, Drawable drawable) {

    }
}
